package com.hskn.hss.module.tlempsalary.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.tlemergentplan.entity.TlEmergentPlan;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlemployee.service.ITlEmployeeService;
import com.hskn.hss.module.tlempsalary.entity.TlEmpSalary;
import com.hskn.hss.module.tlempsalary.mapper.TlEmpSalaryMapper;
import com.hskn.hss.module.tlempsalary.service.ITlEmpSalaryService;
import com.hskn.hss.module.tlempsalary.to.*;
import com.hskn.hss.module.tlempsalary.vo.EmpSalaryExcelOutVO;
import com.hskn.hss.module.tlempsalary.vo.EmpSalaryInExcelOutVO;
import com.hskn.hss.module.tlthreshold.mapper.TlThresholdMapper;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-19
 */
@Api(tags = {"-tl_emp_salary"}, description = "人员基本工资支出薪资明细API")
@Slf4j
@RestController
@RequestMapping("/hss/tlempsalary")
public class TlEmpSalaryController {

    @Autowired
    private ITlEmpSalaryService tlEmpSalaryService;
    @Resource
    private ITlEmployeeService employeeService;
    @Autowired
    private ISysDepartService departService;

    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_emp_salary", bean = TlEmpSalary.class, beanMapper = TlEmpSalaryMapper.class,
            names = "empid", twoBeanMapper = TlEmployeeMapper.class, twoNames = "name", twoTableName = "tl_employee")
    @ApiOperation(value = "新增", notes = "新增数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEmpSalary.class)
    })
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(HttpServletRequest request, @RequestBody @Validated TlEmpSalaryInsertTO salaryInsertTO) {
        try {
            return tlEmpSalaryService.insert(salaryInsertTO);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_emp_salary", idKey = "id", bean = TlEmpSalary.class, beanMapper = TlEmpSalaryMapper.class,
            names = "empid", twoBeanMapper = TlEmployeeMapper.class, twoNames = "name", twoTableName = "tl_employee")
    @ApiOperation(value = "修改", notes = "修改数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEmpSalary.class)
    })
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult<Object> update(HttpServletRequest request, @RequestBody @Validated TlEmpSalaryUpdateTO salaryUpdateTO) {
        try {
            return tlEmpSalaryService.update(salaryUpdateTO);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_emp_salary", idKey = "ids", bean = TlEmpSalary.class, beanMapper = TlEmpSalaryMapper.class,
            names = "empid", twoBeanMapper = TlEmployeeMapper.class, twoNames = "name", twoTableName = "tl_employee")
    @ApiOperation(value = "删除", notes = "删除一条数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEmpSalary.class)
    })
    @RequestMapping(value = "deletebyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebyid(@RequestBody @Validated ForIdsTO forIdsTO) {
        try {
            return tlEmpSalaryService.deletebyid(forIdsTO);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @ApiOperation(value = "详情", notes = "详情数据")
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = TlEmpSalary.class)})
    @RequestMapping(value = "getDetail", method = RequestMethod.POST)
    public AjaxResult<Object> getDetail(@RequestBody @Validated TlEmpSalaryDetailTO salaryDetailTO) {
        TlEmpSalary tlEmpSalary;
        try {
            tlEmpSalary = tlEmpSalaryService.getDetail(salaryDetailTO);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
        return AjaxResult.success(tlEmpSalary);

    }

    @ApiOperation(value = "列表", notes = "列表数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEmpSalary.class)
    })
    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public AjaxResult<Object> getList(@RequestBody @Validated TlEmpSalaryListTO salaryListTO) {
        try {
            JSONObject json = tlEmpSalaryService.getList(salaryListTO);
            return AjaxResult.success(json);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }
    /**
     * 工资组成导入接口
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_emp_salary", bean = TlEmpSalary.class, beanMapper = TlEmpSalaryMapper.class, names = "empid")
    @ApiOperation(value = "工资组成导入接口", notes = "工资组成导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request,@ModelAttribute   @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file=excelReaderTo.getFiles();
            if(Arrays.stream(ExcelTypeEnum.values()).noneMatch(s->s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))){
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlEmpSalary> util = new ExcelUtil<TlEmpSalary>(TlEmpSalary.class);
            List<TlEmpSalary> empSalaryList = util.importExcel(inputStream);
            if(empSalaryList.isEmpty()){
                return AjaxResult.fail("导入内容为空");
            }
            tlEmpSalaryService.excelReader(empSalaryList);
            if ( tlEmpSalaryService.saveBatch(empSalaryList)) {
                return AjaxResult.success();
            }else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        }catch (Exception exception){
            exception.printStackTrace();
            return AjaxResult.fail();
        }

    }
    @ApiOperation(value = "工资组成导出接口", notes = "工资组成导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok" ,response = EmpSalaryExcelOutVO.class)
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request,@RequestBody EmpSalaryListTO empSalaryListTo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if((empSalaryListTo.getIds()!=null&&empSalaryListTo.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            //查询数据
            List<TlEmpSalary> empSalaryList = tlEmpSalaryService.getTlEmpSalary(empSalaryListTo, format);
            //工具类实例化
            ExcelUtil<EmpSalaryExcelOutVO> util = new ExcelUtil<EmpSalaryExcelOutVO>(EmpSalaryExcelOutVO.class);
            //数据载体转换
            List<EmpSalaryExcelOutVO> empSalaryExcelOutVOList=JSONObject.parseArray(JSONObject.toJSONString(empSalaryList),EmpSalaryExcelOutVO.class);
            //构造结果集
            Map<String, SysDepart> departMap=departService.getDepartMap(new QueryWrapper<>());
            Map<String,TlEmployee> employeeMap = employeeService.getEmpMap(new QueryWrapper<>());
            for(EmpSalaryExcelOutVO empSalaryExcelOutVO:empSalaryExcelOutVOList){
                if(departMap.containsKey(empSalaryExcelOutVO.getEmpdeptid())){
                    empSalaryExcelOutVO.setEmpdeptName(departMap.get(empSalaryExcelOutVO.getEmpdeptid()).getDepartName());
                }
                if(employeeMap.containsKey(empSalaryExcelOutVO.getEmpid())){
                    empSalaryExcelOutVO.setWorktypename(employeeMap.get(empSalaryExcelOutVO.getEmpid()).getWorktypename());
                }
                if(employeeMap.containsKey(empSalaryExcelOutVO.getEmpid())){
                    empSalaryExcelOutVO.setEmpName(employeeMap.get(empSalaryExcelOutVO.getEmpid()).getName());
                }
                if(employeeMap.containsKey(empSalaryExcelOutVO.getEmpid())){
                    empSalaryExcelOutVO.setEmplnum(employeeMap.get(empSalaryExcelOutVO.getEmpid()).getEmplnum());
                }
                if(employeeMap.containsKey(empSalaryExcelOutVO.getEmpid())){
                    empSalaryExcelOutVO.setIdcardnum(employeeMap.get(empSalaryExcelOutVO.getEmpid()).getIdcardnum());
                }

            }
            //            导出
            empSalaryExcelOutVOList = empSalaryExcelOutVOList.stream().sorted(Comparator.comparing(EmpSalaryExcelOutVO::getPaydate).reversed()).collect(Collectors.toList());
            return util.exportExcel(empSalaryExcelOutVOList,"工资组成");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
    @ApiOperation(value = "工资组成导出模板接口", notes = "工资组成模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok" ,response = EmpSalaryInExcelOutVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<EmpSalaryInExcelOutVO> util = new ExcelUtil<EmpSalaryInExcelOutVO>(EmpSalaryInExcelOutVO.class);
            //数据载体转换
            List<EmpSalaryInExcelOutVO> empSalaryInExcelOutVOList=new ArrayList<>();
            //导出
            return util.exportExcel(empSalaryInExcelOutVOList,"工资组成模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

